package org.theSeed.web.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.springframework.http.MediaType;
import org.theSeed.base.exp.ServiceExp;
import org.theSeed.base.pojo.constant.SysConstant;
import org.theSeed.base.pojo.vo.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * web响应工具
 */
public class ResponseUtil {
    /**
     * 指定获取ObjectMapper
     */
    @Setter
    private static String objectMapperName = null;

    private static ObjectMapper objectMapper = null;

    /**
     * 获取ObjectMapper
     * @return
     */
    public static ObjectMapper getObjectMapper(){
        if (ObjectUtil.isNull(objectMapper)){
            return getSpringObjectMapper();
        }
        return objectMapper;
    }

    /**
     * 获取spring中的ObjectMapper
     * @return
     */
    public static synchronized ObjectMapper getSpringObjectMapper(){
        if (ObjectUtil.isNull(objectMapper)){
            try {
                objectMapper = SpringUtil.getBean(ObjectMapper.class);
            } catch (Exception e) {
                if (ObjectUtil.isNotEmpty(objectMapperName)){
                    objectMapper = SpringUtil.getBean(objectMapperName);
                }
                throw new ServiceExp("获取序列化器异常");
            }
            return getSpringObjectMapper();
        }
        throw new ServiceExp("ObjectMapper序列化器不存在");
    }

    /**
     * 响应输出
     * @param response
     * @param res
     * @throws IOException
     */
    public static void writeResponse(final HttpServletResponse response, R res) throws IOException {
        response.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName(SysConstant.SYSTEM_CODE)).toString());
        ServletOutputStream os = response.getOutputStream();
        ObjectMapper objectMapper = SpringUtil.getBean(ObjectMapper.class);
        os.write(SpringUtil.getBean(ObjectMapper.class).writeValueAsBytes(res));
        os.flush();
    }
}
